<template>
  <div class="dailyanalytics coinrevenue-list">
    <div class="search-box">
      <Row type="flex"
           justify="start"
           class="coinrevenue-list-edit">
        <Row type="flex"
             align="middle">
          <Col>
          <span>时间：</span>
          </Col>
          <Col class="concrete-data">
          <DatePicker type="date"
                      v-model="searchObj.dayTimes"
                      @on-change="seletetime"
                      format="yyyy-MM-dd"
                      placement="bottom-end"
                      :options="optionsStartTimeDay"
                      :editable='false'
                      placeholder="请选择时间"
                      style="width: 180px"></DatePicker>
          </Col>
          <Row type="flex"
               align="middle"
               class="export-btn">
            <Col>
            <span>门店名称：</span>
            </Col>
            <Col>
            <vueTreeselectChoice :max-tag-count='1'
                                 componentsType='iselect'
                                 :filterable="true"
                                 @on-change="handleShop"
                                 @on-api-finish="apiFinish"
                                 permissionCode="moms:report:coinanalytics"
                                 v-model="searchObj.shopId"></vueTreeselectChoice>
            <!-- <vueTreeselectChoice :disable-branch-nodes="true"
                                 style="display:inline-block;padding-top:8px;"
                                 :clearable='false'
                                 @input='search'
                                 @on-api-finish="apiFinish"
                                 permissionCode="moms:report:coinanalytics"
                                 v-model="searchObj.shopId"></vueTreeselectChoice> -->
            <!-- <Select v-model="searchObj.shopId"
                    filterable
                    @on-change="selectshop"
                    class="select-shop-item">
              <Option v-for="item in shopList"
                      :value="item.shopId"
                      :key="item.shopId">{{ item.shopName }}</Option>
            </Select> -->
            </Col>
          </Row>
        </Row>
        <Row type="flex"
             align="middle">
          <Col style="padding-left:30px;">
          <Button type="primary"
                  class="coinrevenue-btn"
                  @click="search">查询</Button>
          <!-- <Button class="coinrevenue-btn export-btn">导出</Button> -->
          </Col>
        </Row>
      </Row>
    </div>

    <div id="gamecurrencyAnalysis"
         v-show="contentShow"
         style="position:relative">
      <p class="dailyanalytics-title dailyanalytics-title-bg">
        <span class="chart-title-icon"></span>
        <span class="chart-title-name">游戏币出入库分类构成图</span>
      </p>
      <div class="dailyanalytics-chart"
           v-show="isEchart">
        <div class="dailyanalytics-chart-div">
          <div id="currencyTerm"
               class="chart-pie">
          </div>
          <div class="dailyanalytics-chart-legend">
            <div class="legend-li"
                 v-for="(item,index) in paymentApproachList"
                 :key="index">
              <span class="legend-icon"
                    :style="{'background-color':item.color}"></span>
              <span class="legend-title">{{item.payCode}}</span>
              <span class="legend-total">{{item.revenue!==null?item.revenue:'0.00'}}</span>
              <span class="legend-percentage"
                    v-if="item.payCode!=='合计'">{{item.percent!==null?item.percent:0}}%</span>
            </div>
          </div>
        </div>
        <div class="dailyanalytics-chart-div">
          <div id="salesdChannels"
               class="chart-pie">
          </div>
          <div class="dailyanalytics-chart-legend">
            <div class="legend-li"
                 v-for="(item,index) in revenueChannelList"
                 :key="index">
              <span class="legend-icon"
                    :style="{'background-color':item.color}"></span>
              <span class="legend-title">{{item.payCode}}</span>
              <span class="legend-total">{{item.revenue}}</span>
              <span class="legend-percentage"
                    v-if="item.payCode!=='合计'">{{item.percent===null?0:item.percent}}%</span>
            </div>
          </div>
        </div>
      </div>
      <div class="dailyanalytics-chart-nodata"
           v-show="!isEchart">暂无数据</div>
      <p class="dailyanalytics-title dailyanalytics-title-bg">
        <span class="chart-title-icon"></span>
        <span class="chart-title-name">当日游戏币出入库统计</span>
      </p>
      <div class="gamecurrencyTable">
        <!-- <template> -->
        <div class="gamecurrencyTable-cont">
          <Table :columns="columns1"
                 :data="data1">
          </Table>
        </div>
        <!-- </template> -->
      </div>
      <p class="dailyanalytics-title dailyanalytics-title-bg">
        <span class="chart-title-icon"></span>
        <span class="chart-title-name">分类统计</span>
      </p>
      <div class="gamecurrencyTable">
        <zk-table class="gamecurrencyTable-cont"
                  ref="table"
                  sum-text="sum"
                  index-text="#"
                  :data="data2"
                  :columns="columns2"
                  :stripe="props.stripe"
                  :border="props.border"
                  :show-header="props.showHeader"
                  :show-summary="props.showSummary"
                  :show-row-hover="props.showRowHover"
                  :show-index="props.showIndex"
                  :tree-type="props.treeType"
                  :is-fold="props.isFold"
                  :expand-type="props.expandType"
                  :selection-type="props.selectionType">
          <template slot="receiveNum"
                    slot-scope="scope">
            <span class="receiveNum"
                  @click="jumpReceive(scope.row)">{{scope.row.receiveNum}}</span>
          </template>
          <template slot="withdrawNum"
                    slot-scope="scope">
            <span class="withdrawNum"
                  @click="jumpAppera(scope.row)">{{scope.row.withdrawNum}}</span>
          </template>
          <template slot="depositNum"
                    slot-scope="scope">
            <span class="depositNum"
                  @click="jumpEnter(scope.row)">{{scope.row.depositNum}}</span>
          </template>
        </zk-table>
      </div>
      <Spin size="large"
            fix
            v-if="spinShow"></Spin>
    </div>
    <div v-show="!contentShow"
         style="text-align: center;margin-top:114px;">
      <img :width="320"
           :height="240"
           :src="error">
    </div>
  </div>
</template>
<script>
// import { rowSpanTable, formatRowspanData } from '@/libs/rowspan'
import { getShopList } from '@/api/system/store'
import { formatDate } from '@/libs/tools'
import echarts from 'echarts'
import ZkTable from 'vue-table-with-tree-grid'
import { shopConinDaily, shopCoinCashier } from '@/api/report/shop'
import error from '@/assets/images/error-page/error-shop.svg'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
export default {
  name: 'report_shop_gamecurrency',
  components: { ZkTable, vueTreeselectChoice },
  data () {
    return {
      shopList: [],
      total: 0,
      isloading: false,
      spinShow: false,
      chart: null,
      contentShow: false,
      error: error,
      myEchart1: '',
      myEchart2: '',
      isEchart: true,
      colorList: ['#2D8CF0', '#2D56F9', '#6A7FD1', '#18BE6B', '#BABE18', '#5A9F46', '#FF9901', '#FFBB01', '#FFBB01', '#C42DF0', '#F02D96', '#8559BA', '#ED4014', '#EDE614', '#D49955'],
      columns1: [
        { title: '总出库数', key: 'takeStockNum', align: 'center' },
        { title: '总销售数', key: 'saleNum', align: 'center' },
        { title: '总存币数', key: 'depositNum', align: 'center' },
        { title: '总取币数', key: 'withdrawNum', align: 'center' },
        { title: '机台总收币数', key: 'machineReceiveNum', align: 'center' },
        { title: '总入库数', key: 'putStockNum', align: 'center' },
        { title: '总差异数', key: 'diffNum', align: 'center' }
      ],
      optionsStartTimeDay: {
        disabledDate (date) {
          return date && date.valueOf() > Date.now()
        }
      },
      data1: [
      ],
      props: {
        stripe: true, // 是否显示间隔斑马纹
        border: false, // 是否显示纵向边框
        showHeader: true, // 是否显示表头
        showSummary: false, // 是否显示表尾合计行
        showRowHover: true, // 鼠标悬停时，是否高亮当前行
        showIndex: false, // 是否显示数据索引
        treeType: true, // 是否为树形表格
        isFold: false, // 树形表格中父级是否默认折叠
        expandType: false, // 是否为展开行类型表格（为 True 时，需要添加作用域插槽, 它可以获取到 row, rowIndex)
        selectionType: false // 是否显示间隔斑马纹
      },
      data2: [
      ],
      cashierList: [],
      outBoundData: [], // 出库数据
      outBoundDataTatal: 0, // 出库数据总计
      wareHousingData: [], // 入库数据
      wareHousingDataTatal: 0, // 入库数据总计
      columns2: [
        {
          label: '分类',
          prop: 'cashierName',
          minWidth: '200px'
        },
        {
          label: '昨日留币',
          prop: 'yesterdayLeftNum'
        },
        {
          label: '领用数',
          prop: 'receiveNum',
          type: 'template',
          template: 'receiveNum'
        },
        {
          label: '出币数',
          prop: 'withdrawNum',
          type: 'template',
          template: 'withdrawNum'
        },
        {
          label: '入币数',
          prop: 'depositNum',
          type: 'template',
          template: 'depositNum'
        },
        {
          label: '清币数',
          prop: 'clearNum'
        },
        {
          label: '入库数',
          prop: 'putStockNum'
        },
        {
          label: '差异数',
          prop: 'diffNum'
        }
      ],
      paymentApproachListTotal: 0,
      paymentApproachList: [],
      revenueChannelList: [],
      searchObj: {
        offset: 1,
        limit: 10,
        dayTimes: formatDate(new Date(new Date().getTime()), 'yyyy-MM-dd'),
        startDate: '',
        endDate: '',
        pageSize: 10,
        shopId: null
      }
    }
  },
  mounted () {
    this.searchObj.startDate = formatDate(this.searchObj.dayTimes, 'yyyy-MM-dd') + ' 00:00:00'
    this.searchObj.endDate = formatDate(new Date(new Date(this.searchObj.dayTimes).getTime() + 86400000), 'yyyy-MM-dd') + ' 00:00:00'
    if (this.$store.state.user.orgType === 1) {
      this.searchObj.shopId = this.$store.state.user.orgId
      this.search()
    }
  },
  methods: {
    setshopId () {
      if (this.$store.state.user.orgType === '0') {
        this.searchObj.shopId = null
      } else {
        this.searchObj.shopId = this.$store.state.user.orgId
      }
    },
    apiFinish (isId) {
      // this.ShopValue = this.$store.state.user.orgId
      // this.ShopValue = [this.$store.state.user.orgId]
    },
    // 游戏币出库
    getPaymentTerm () {
      let paymentApproachListData = []
      let paymentApproachListDataColor = []
      for (let index = 0; index < this.paymentApproachList.length; index++) {
        const element = this.paymentApproachList[index]
        if (element.payCode !== '合计') {
          paymentApproachListData.push({ name: element.payCode, value: element.percent })
          paymentApproachListDataColor.push(element.color)
        }
      }
      this.myEchart1 = echarts.init(document.getElementById('currencyTerm')) // 收款方式
      let option = {
        title: {
          text: '游戏币出库',
          x: 'center',
          y: 'center',
          itemGap: 20,
          textStyle: {
            color: '#808695',
            fontFamily: '微软雅黑',
            fontSize: 12
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}：{c}%'
        },
        color: paymentApproachListDataColor,
        series: [
          {
            name: '游戏币出库',
            type: 'pie',
            radius: ['30%', '55%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: paymentApproachListData
          }
        ]
      }
      this.myEchart1.setOption(option)
      window.addEventListener('resize', () => {
        this.myEchart1.resize()
      })
    },
    async handleShop () {
      this.searchObj.offset = 1
      this.searchObj.limit = 10
      this.search()
    },
    // 跳转领用数
    jumpReceive (row) {
      localStorage.setItem('receiveNumber', JSON.stringify({ id: [this.searchObj.shopId], dayTimes: this.searchObj.dayTimes, cashierId: row.cashierId }))
      this.$router.push({
        name: 'report_shop_gamecurrency_receive_number',
        params: { id: row.cashierType }
      })
    },
    // 跳转出币数
    jumpAppera (row) {
      localStorage.setItem('apperaCurrency', JSON.stringify({ id: [this.searchObj.shopId], dayTimes: this.searchObj.dayTimes, cashierId: row.cashierId }))
      this.$router.push({
        name: 'report_shop_gamecurrency_appear_currency',
        params: { id: row.cashierType }
      })
    },
    // 跳转入币数
    jumpEnter (row) {
      localStorage.setItem('enterCurrency', JSON.stringify({ id: [this.searchObj.shopId], dayTimes: this.searchObj.dayTimes, cashierId: row.cashierId }))
      this.$router.push({
        name: 'report_shop_gamecurrency_enter_currency',
        params: { id: row.cashierType }
      })
    },
    // 游戏币入库
    getSalesChannels () {
      let revenueChannelListData = []
      let revenueChannelListDataColor = []
      for (let index = 0; index < this.revenueChannelList.length; index++) {
        const element = this.revenueChannelList[index]
        if (element.payCode !== '合计') {
          revenueChannelListData.push({ name: element.payCode, value: element.percent })
          revenueChannelListDataColor.push(element.color)
        }
      }
      this.myEchart2 = echarts.init(document.getElementById('salesdChannels')) // 营收渠道
      let salesChannelsOption = {
        title: {
          text: '游戏币入库',
          x: 'center',
          y: 'center',
          itemGap: 20,
          textStyle: {
            color: '#808695',
            fontFamily: '微软雅黑',
            fontSize: 12
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}：{c}%'
        },
        color: revenueChannelListDataColor,
        series: [
          {
            name: '游戏币入库',
            type: 'pie',
            radius: ['30%', '55%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: revenueChannelListData
          }
        ]
      }
      this.myEchart2.setOption(salesChannelsOption) // 营收渠道
      window.addEventListener('resize', () => {
        this.myEchart2.resize() // 营收渠道
      })
    },
    maxTagPlaceholder (num) {
      return '...'
    },
    seletetime (val) {
      this.searchObj.startDate = formatDate(this.searchObj.dayTimes, 'yyyy-MM-dd') + ' 00:00:00'
      this.searchObj.endDate = formatDate(new Date(new Date(this.searchObj.dayTimes).getTime() + 86400000), 'yyyy-MM-dd') + ' 00:00:00'
    },
    search () {
      this.contentShow = false
      if (!this.searchObj.dayTimes) {
        this.$Message.error(`请选择日期`)
      } else if (!this.searchObj.shopId) {
        return false
      } else {
        this.contentShow = true
        this.getStock()
        if (this.cashierList.length) {
          this.$nextTick(() => {
            this.myEchart1.resize()
            this.myEchart2.resize()
          })
        }
      }
    },
    // 游戏币出入库统计查询
    getStock () {
      this.data1 = []
      this.outBoundData = []
      this.outBoundDataTatal = 0
      this.wareHousingData = []
      this.wareHousingDataTatal = 0
      this.paymentApproachList = []
      this.revenueChannelList = []
      this.spinShow = true
      shopConinDaily({
        merchantId: this.$store.state.user.merchantId,
        shopIds: [this.searchObj.shopId],
        startDate: this.searchObj.startDate,
        endDate: this.searchObj.endDate
      }).then(res => {
        if (res.data.status === 200) {
          if (!res.data.data) {
            this.data1 = []
          } else {
            this.data1.push(res.data.data)
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
      shopCoinCashier({
        merchantId: this.$store.state.user.merchantId,
        shopIds: [this.searchObj.shopId],
        startDate: this.searchObj.startDate,
        endDate: this.searchObj.endDate
      }).then(res => {
        if (res.data.status === 200) {
          this.cashierList = res.data.data
          if (this.cashierList.length) {
            this.isEchart = true
            this.cashierList.forEach(ele => {
              if (!ele.cashierName) {
                ele.cashierName = ['收银台', '兑奖台', '一体机', '取币机', '存币机', '其他'][ele.cashierType]
              }
              // if (!ele.cashierName) {
              // if (ele.cashierName === '收银台' || ele.cashierName === '兑奖台' || ele.cashierName === '一体机') {
              this.outBoundData.push({
                name: ele.cashierName,
                receiveNum: ele.receiveNum
              })
              this.wareHousingData.push({
                name: ele.cashierName,
                receiveNum: ele.putStockNum
              })
              // }
              // }
            })
            this.setEchartsOne()
            this.setEchartsTwo()
          } else {
            this.isEchart = false
            this.paymentApproachList = []
            this.revenueChannelList = []
          }
          this.data2 = this.cashierList
          this.getPaymentTerm()
          this.getSalesChannels()
          this.$nextTick(() => {
            this.myEchart1.resize()
            this.myEchart2.resize()
          })
          this.spinShow = false
        } else {
          // this.spinShow = false
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    // 入库图表
    setEchartsOne () {
      this.outBoundData.forEach(ele => {
        this.outBoundDataTatal += ele.receiveNum
        this.paymentApproachList.push({
          payCode: ele.name,
          revenue: ele.receiveNum,
          percent: '',
          color: ''
        })
      })
      this.paymentApproachList.push({
        payCode: '合计',
        revenue: this.outBoundDataTatal,
        percent: '100',
        color: ''
      })
      this.paymentApproachList.forEach((ele, idx, art) => {
        ele.percent = ele.revenue ? ((ele.revenue / this.outBoundDataTatal) * 100).toFixed(2) : 0
        art[idx].color = this.colorList[idx]
      })
    },
    // 出库图表
    setEchartsTwo () {
      this.wareHousingData.forEach(ele => {
        this.wareHousingDataTatal += ele.receiveNum
        this.revenueChannelList.push({
          payCode: ele.name,
          revenue: ele.receiveNum,
          percent: '',
          color: ''
        })
      })
      this.revenueChannelList.push({
        payCode: '合计',
        revenue: this.wareHousingDataTatal,
        percent: '100',
        color: '#17233D'
      })
      this.revenueChannelList.forEach((ele, idx, art) => {
        ele.percent = ele.revenue ? ((ele.revenue / this.wareHousingDataTatal) * 100).toFixed(2) : 0
        art[idx].color = this.colorList[idx]
      })
    },
    getShopList () {
      this.tableHeight = 0
      getShopList({
        permissionCode: 'moms:report:coinanalytics', // 查看普通订单
        merchantId: this.$store.state.user.merchantId, // 商户id
        offset: 0,
        limit: 9999
      })
        .then(res => {
          if (res.data.status === 200) {
            // if (res.data.totalCount > 0) {
            this.shopList = res.data.data
            this.shopList.forEach(ele => {
              if (ele.shopId === this.$store.state.user.orgId) {
                this.contentShow = true
              }
            })
            this.getStock()
            this.shopList.forEach(ele => {
              console.log('ss', ele.cashierType)
              if (!ele.cashierName) {
                this.$set(ele, 'cashierName', ele.cashierType)
              }
            })
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
        .catch(error => {
          this.$Message.error(`${error}`)
        })
    }
  }
}
</script>
<style lang="less" scoped>
.dailyanalytics {
  .coinrevenue-list-edit {
    padding: 0 24px;
    height: 80px;
    .export-btn {
      margin-left: 24px;
    }
  }
  .dailyanalytics-title-bg {
    background: #f8f8f9;
    .chart-title-icon {
      margin-left: 40px;
    }
  }
  .dailyanalytics-title {
    height: 48px;
    line-height: 48px;
    width: 100%;
    .chart-title-icon {
      display: inline-block;
      width: 8px;
      height: 20px;
      background: #2d8cf0;
      vertical-align: middle;
    }
    .chart-title-name {
      display: inline-block;
      font-size: 14px;
      color: #464c5b;
      letter-spacing: 0;
      text-align: justify;
      margin-left: 10px;
      vertical-align: middle;
    }
  }
  .dailyanalytics-chart {
    width: 100%;
  }
  .dailyanalytics-chart-nodata {
    text-align: center;
    padding: 50px 0;
  }
  .dailyanalytics-chart-div {
    display: inline-block;
    width: 50%;
    position: relative;
  }
  .dailyanalytics-chart-li {
    position: relative;
    float: left;
    width: 33.3%;
  }
  .dailyanalytics-chart-legend {
    position: absolute;
    top: 10px;
    left: 45%;
    text-align: left;
    display: flex;
    justify-content: center;
    flex-direction: column;
    height: 350px;
    // margin-left: 30px;
  }
  .chart-legend-detail {
    float: left;
    width: 100%;
  }
  .dailyanalytics-chart-legend-li {
    float: left;
    width: 100%;
    text-align: right;
    .legend-li {
      float: left;
      width: 50%;
    }
  }
  .legend-chart-li {
    width: 50%;
    margin: 0 auto;
    text-align: right;
  }
  .legend-li {
    width: 100%;
    margin-bottom: 27px;
    .legend-icon {
      display: inline-block;
      width: 12px;
      height: 12px;
    }
    .legend-title {
      display: inline-block;
      width: 100px;
      font-size: 12px;
      color: #464c5b;
      margin-left: 10px;
      text-align: justify;
    }
    .legend-total {
      display: inline-block;
      width: 100px;
      font-size: 14px;
      color: #464c5b;
      letter-spacing: 0;
      text-align: justify;
    }
    .legend-percentage {
      display: inline-block;
      font-size: 12px;
      color: #808695;
      letter-spacing: 0;
      text-align: justify;
      margin-left: 10px;
    }
  }
  .chart-pie {
    width: 40%;
    height: 350px;
    // width: 230px;
    /* border: 1px solid red; */
  }
  .chart-pie1 {
    width: 60%;
    // width:230px;
    height: 350px;
    margin: 0 auto;
  }
  .gamecurrencyTable {
    background: #ffffff;
    padding: 40px 0;
    width: 100%;
    .gamecurrencyTable-cont {
      width: 80%;
      margin: auto;
    }
  }
}
</style>
<style lang="less">
.select-shop-item {
  height: 35px;
  width: 210px;
  .ivu-select-selection {
    height: 35px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .ivu-tag {
    max-width: 100px;
  }
}
</style>
<style>
.dailyanalytics .zk-icon-plus-square-o:before {
  content: '\e625';
}
.dailyanalytics .zk-icon-minus-square-o:before {
  content: '\e668';
}
.zk-table__cell-inner .receiveNum {
  color: #2d8cf0;
  cursor: pointer;
  text-decoration: underline #2d8cf0;
}
.zk-table__cell-inner .withdrawNum {
  color: #2d8cf0;
  cursor: pointer;
  text-decoration: underline #2d8cf0;
}
.zk-table__cell-inner .depositNum {
  color: #2d8cf0;
  cursor: pointer;
  text-decoration: underline #2d8cf0;
}
</style>
